﻿using System;
using System.Text;

namespace Jodell.Lua
{
    public class Lua_Converter
    {
        public static Int16 ToInt16(byte[] datas, int offset)
        {
            for (int i = 0; i < sizeof(UInt16) / 2; i++)
            {
                (datas[i * 2 + 1 + offset], datas[i * 2 + offset]) = (datas[i * 2 + offset], datas[i * 2 + 1 + offset]);
            }
            return BitConverter.ToInt16(datas, offset);
        }
        public static UInt16 ToUInt16(byte[] datas, int offset)
        {
            for (int i = 0; i < sizeof(UInt16) / 2; i++)
            {
                (datas[i * 2 + 1 + offset], datas[i * 2 + offset]) = (datas[i * 2 + offset], datas[i * 2 + 1 + offset]);
            }
            return BitConverter.ToUInt16(datas, offset);
        }
        public static Int32 ToInt32(byte[] datas, int offset)
        {
            for (int i = 0; i < sizeof(Int32) / 2; i++)
            {
                (datas[i * 2 + 1 + offset], datas[i * 2 + offset]) = (datas[i * 2 + offset], datas[i * 2 + 1 + offset]);
            }
            return BitConverter.ToInt32(datas, offset);
        }
        public static UInt32 ToUInt32(byte[] datas, int offset)
        {
            for (int i = 0; i < sizeof(UInt32) / 2; i++)
            {
                (datas[i * 2 + 1 + offset], datas[i * 2 + offset]) = (datas[i * 2 + offset], datas[i * 2 + 1 + offset]);
            }
            return BitConverter.ToUInt32(datas, offset);
        }
        public static float ToFloat(byte[] datas, int offset)
        {
            for (int i = 0; i < sizeof(Single) / 2; i++)
            {
                (datas[i * 2 + 1 + offset], datas[i * 2 + offset]) = (datas[i * 2 + offset], datas[i * 2 + 1 + offset]);
            }
            return BitConverter.ToSingle(datas, offset); ;
        }
        public static Double ToDouble(byte[] datas, int offset)
        {
            for (int i = 0; i < sizeof(Double) / 2; i++)
            {
                (datas[i * 2 + 1 + offset], datas[i * 2 + offset]) = (datas[i * 2 + offset], datas[i * 2 + 1 + offset]);
            }
            return BitConverter.ToDouble(datas, offset); ;
        }
        public static string ToHexString(byte[] datas, int offset, int count)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < count; i++)
            {
                sb.Append(datas[i + offset].ToString("X2"));
                sb.Append(' ');
            }
            return sb.ToString();
        }
        public static string ToString(byte[] datas, int offset, int count)
        {
            for (int i = 0; i < count / 2; i++)
            {
                (datas[i * 2 + 1 + offset], datas[i * 2 + offset]) = (datas[i * 2 + offset], datas[i * 2 + 1 + offset]);
            }
            return Encoding.UTF8.GetString(datas, offset, count);
        }
    }
}
